import React, { useState } from 'react';
import { Form, Select, Input, Button, Space, Table, Popconfirm } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { FormInstance } from 'antd/es/form';

const { Option } = Select;

interface AggregateConfigStepProps {
  form: FormInstance;
}

const AggregateConfigStep: React.FC<AggregateConfigStepProps> = ({ form }) => {
  const [aggregateModalVisible, setAggregateModalVisible] = useState(false);
  const [editingAggregate, setEditingAggregate] = useState<any>(null);

  const aggregateFunctions = [
    { value: 'COUNT', label: '计数' },
    { value: 'SUM', label: '求和' },
    { value: 'AVG', label: '平均值' },
    { value: 'MAX', label: '最大值' },
    { value: 'MIN', label: '最小值' },
    { value: 'COUNT_DISTINCT', label: '去重计数' },
  ];

  const aggregates = form.getFieldValue('aggregates') || [];
  const tables = form.getFieldValue('tables') || [];

  const handleAddAggregate = () => {
    setEditingAggregate({
      id: Date.now().toString(),
      function: 'COUNT',
      tableName: '',
      fieldName: '',
      alias: '',
    });
    setAggregateModalVisible(true);
  };

  const handleEditAggregate = (aggregate: any) => {
    setEditingAggregate(aggregate);
    setAggregateModalVisible(true);
  };

  const handleDeleteAggregate = (aggregateId: string) => {
    const currentAggregates = form.getFieldValue('aggregates') || [];
    const newAggregates = currentAggregates.filter((item: any) => item.id !== aggregateId);
    form.setFieldValue('aggregates', newAggregates);
  };

  const handleSaveAggregate = (aggregate: any) => {
    const currentAggregates = form.getFieldValue('aggregates') || [];
    if (editingAggregate && editingAggregate.id) {
      // 编辑现有聚合函数
      const index = currentAggregates.findIndex((item: any) => item.id === aggregate.id);
      if (index !== -1) {
        currentAggregates[index] = aggregate;
      }
    } else {
      // 添加新聚合函数
      currentAggregates.push(aggregate);
    }
    form.setFieldValue('aggregates', currentAggregates);
    setAggregateModalVisible(false);
    setEditingAggregate(null);
  };

  const columns = [
    {
      title: '序号',
      key: 'index',
      width: 60,
      render: (_: any, __: any, index: number) => index + 1,
    },
    {
      title: '聚合函数',
      dataIndex: 'function',
      key: 'function',
      width: 120,
      render: (func: string) => {
        const option = aggregateFunctions.find(opt => opt.value === func);
        return option ? option.label : func;
      },
    },
    {
      title: '数据表',
      dataIndex: 'tableName',
      key: 'tableName',
      width: 120,
    },
    {
      title: '字段',
      dataIndex: 'fieldName',
      key: 'fieldName',
      width: 120,
    },
    {
      title: '别名',
      dataIndex: 'alias',
      key: 'alias',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: any) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            onClick={() => handleEditAggregate(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个聚合函数吗？"
            onConfirm={() => handleDeleteAggregate(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAddAggregate}
        >
          添加聚合函数
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={aggregates}
        rowKey="id"
        pagination={false}
        locale={{
          emptyText: '暂无聚合函数',
        }}
      />

      {/* 聚合函数编辑弹窗 */}
      {aggregateModalVisible && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 1000,
        }}>
          <div style={{
            backgroundColor: 'white',
            padding: 24,
            borderRadius: 8,
            width: 500,
          }}>
            <h3>{editingAggregate?.id ? '编辑聚合函数' : '添加聚合函数'}</h3>
            <Form
              layout="vertical"
              initialValues={editingAggregate}
              onFinish={handleSaveAggregate}
            >
              <Form.Item
                name="function"
                label="聚合函数"
                rules={[{ required: true, message: '请选择聚合函数' }]}
              >
                <Select placeholder="请选择聚合函数">
                  {aggregateFunctions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item
                name="tableName"
                label="数据表"
                rules={[{ required: true, message: '请选择数据表' }]}
              >
                <Select placeholder="请选择数据表">
                  {tables.map((table: string) => (
                    <Option key={table} value={table}>{table}</Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item
                name="fieldName"
                label="字段名"
                rules={[{ required: true, message: '请输入字段名' }]}
              >
                <Input placeholder="请输入字段名" />
              </Form.Item>

              <Form.Item
                name="alias"
                label="别名"
                rules={[{ required: true, message: '请输入别名' }]}
              >
                <Input placeholder="请输入别名" />
              </Form.Item>

              <Form.Item>
                <Space>
                  <Button onClick={() => setAggregateModalVisible(false)}>
                    取消
                  </Button>
                  <Button type="primary" htmlType="submit">
                    保存
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </div>
        </div>
      )}
    </div>
  );
};

export default AggregateConfigStep;